/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
import { useState, useMemo, useEffect } from 'react';

type INeedAuth = string | string[];

const useAuth = (needAuth: INeedAuth, menu: any): boolean => {
    const [authList, setAuthList] = useState<string[]>([]);

    useEffect(() => {
        // 调用后端 API 获取最新的权限列表
        // console.log('permissions', menu?.permissions)
        setAuthList(menu?.permissions || []);
    }, [menu]);

    const auths = useMemo(() => {
        return new Set(authList);
    }, [authList]);

    const hasAuth = (auth: string | string[]): boolean => {
        if (typeof auth === 'string') {
            return auths.has(auth);
        } else {
            return auth.some((a) => auths.has(a));
        }
    };

    if (!authList.length) {
        return true;
    }

    if (Array.isArray(needAuth) || typeof needAuth === 'string') {
        return hasAuth(needAuth);
    } else {
        return Object.values(needAuth).some((auth: any) => hasAuth(auth));
    }

};

export default useAuth;
